﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Oliving.Edge.IServices.SystemBase;
using Oliving.Edge.Model.File;
using Oliving.Edge.Model.Models.SystemBase;
using Oliving.Edge.VModel;

namespace Oliving.Edge.Controllers.Other
{
    [Route("api/[controller]")]
    [ApiController]
    public class FileUploadController : ControllerBase
    {
        private readonly EdgeFileOptions _Options;
        private readonly ISysFileServices _Services;
        public FileUploadController(IOptions<EdgeFileOptions> options, ISysFileServices Services)
        {
            _Services = Services;
            this._Options = options.Value;
        }




        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="file">来自form表单的文件信息</param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Post([FromForm] IFormFile file)
        {
            if (file.Length <= this._Options.MaxSize)//检查文件大小
            {
                var suffix = Path.GetExtension(file.FileName);//提取上传的文件文件后缀
                if (this._Options.FileTypes.IndexOf(suffix) >= 0)//检查文件格式
                {
                    //CombineIdHelper combineId = new CombineIdHelper();//我自己的combine id生成器

                    string filePath = $@"{this._Options.FileBaseUrl}\_{DateTime.Now.ToString("yyyyMMddHHmmssffff")}_{Guid.NewGuid().ToString("N")}_{file.FileName}";
                    SysFile dto = new SysFile()
                    {
                        FileSize = Convert.ToInt32(file.Length),
                        RelativePath = filePath


                    };

                    _Services.Add(dto);

                    //注意路径里面最好不要有中文
                    using (FileStream fs = System.IO.File.Create(filePath))
                    {
                        file.CopyTo(fs);//将上传的文件文件流，复制到fs中
                        fs.Flush();//清空文件流
                    }
                    return StatusCode(200, new { newFileName = $"{"EdgeFile"}{suffix}", SysFileID = dto.ID });//将新文件文件名回传给前端
                }
                else
                    return StatusCode(415, new { msg = "不支持此文件类型" });//类型不正确
            }
            else
                return StatusCode(413, new { msg = $"文件大小不得超过{this._Options.MaxSize / (1024f * 1024f)}M" });//请求体过大，文件大小超标
        }





    }
}